import { NextApiRequest, NextApiResponse } from 'next';
import prisma from '../../../lib/prisma';
import { log } from 'node:console';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== 'POST') {
        return res.status(405).json({ message: 'Method not allowed' });
    }

    let { userId } = req.body;

    userId = parseInt(userId, 10);

    if (isNaN(userId)) {
        return res.status(400).json({ message: 'Invalid input' });
    }

    try {
        const user = await prisma.user.findUnique({
            where: { id: userId },
            select: { score: true },
        });

        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }

        const allUsers = await prisma.user.findMany({
            orderBy: { score: 'desc' },
            select: { id: true, userId: true, score: true },
        });

        const userRank = allUsers.findIndex(u => u.id === userId) + 1;

        const topUsers = allUsers.slice(0, 20).map((u, index) => ({
            id: u.id,
            userId: u.userId,
            score: u.score,
            rank: index + 1,
        }));

        return res.status(200).json({userScore: user.score, userRank, topUsers });
    } catch (error) {
        log(error);
        return res.status(500).json({ message: 'Internal server error', error });
    }
}